<script>
import addtable from '@/mixins/addtable'
import AjaxStore from '@/utils/store/proxyAjax'
import Dialog from '@/components/Dialog'
import ConditionConfig from './refactor/conditionConfig'
import TableFieldAuth from './tablefieldauth/tablefieldauth.vue'
import addtableright from './refactor/addtableright'
import store from './store'
import { deepClone } from '@/utils'
import handle from './event/handle.js'

export default {
  name: 'datagroup',
  mixins: [addtable, store, handle],
  components: {
    Dialog,
    ConditionConfig,
    TableFieldAuth,
    addtableright
  },
  data() {
    return {
      selectedList: [],
      tableSelectionCol: false,
      tableOptWidth: '170',
      labelWidth: '90px',
      idKey: 'datagroupId',
      delIdKey: 'datagroupId',
      delListIdKey: 'datagroupIds',
      recordDialogType: '',
      datagroupName: '',
      datagroupId: '',
      addUrl: '/v1/yq/datagroup/add',
      updateUrl: '/v1/yq/datagroup/update',
      delUrl: '/v1/yq/datagroup/delete',
      delListUrl: '/v1/yq/datagroup/deleteList',
      getCodeTypeListUrl: '/v1/dataProvider/getCodeTypeList',
      resultsymbolUrl: '/v1/yq/resultsymbol/cykablyat',
      businessobjectUrl: '/v1/yq/meatbustype/query',
      addTableConfigUrl: '/v1/yq/datagroup/addTableConfig',
      addBatchTableConfigUrl: '/v1/yq/datagroup/addBatchTableConfig',
      // codeTypeListData: [],
      // resultsymbolData: [],
      // businessobjectData: [],

      url: '/v1/yq/datagroup/findById',
      store: new AjaxStore({
        url: '/v1/yq/datagroup/query'
      }),
      columns: [
        {
          prop: 'datagroupCode',
          label: '编码',
          sortable: true,
          'header-align': 'center',
          width: '240',
          'show-overflow-tooltip': true,
          align: 'left'
        },
        {
          prop: 'datagroupName',
          label: '名称',
          sortable: true,
          'header-align': 'center',
          width: '240',
          align: 'left'
        },
        {
          prop: 'datagroupNote',
          label: '描述',
          sortable: true,
          'header-align': 'center',
          'min-width': '200',
          align: 'left'
        },
        {
          prop: 'name',
          label: '已分配站点',
          sortable: true,
          'header-align': 'center',
          'min-width': '260',
          align: 'left',
          scopedSlots: {
            default: ({ row, $index }) => (
              <c-popover
                trigger='hover'
                ref='popover'
                on-show={this.showContent.bind(this, $index, row.name)}
                placement='top'
                popper-class={this.setClassName($index)}>
                {row.name}
                <div slot='reference' class='name-wrapper table-name'>
                  {row.name}
                </div>
              </c-popover>
            )
          }
        },
        {
          prop: 'isEnable',
          label: '状态',
          width: '120',
          formatter: (row, column, cellValue) =>
            cellValue == 1 ? '启用' : '未启用',
          'header-align': 'center',
          align: 'center',
          width: '100'
        }
      ],
      searchFields: [],
      searchModel: {},

      searchBtnList: [],
      toolPanelBtnList: this.toolPanelBtns,
      tableRowBtnList: this.tableRowBtns,
      showInputFlag: true,
      inputPlaceholder: '输入编码或名称搜索',
      formPanel: {
        add: {
          model: {
            datagroupCode: '',
            datagroupName: '',
            datagroupNote: '',
            isEnable: 1
          },
          fields: [
            {
              label: '数据组编码',
              prop: 'datagroupCode',
              placeholder: '请输入数据组编码',
              anchor: 24,
              ref: 'funId'
            },
            {
              label: '数据组名称',
              prop: 'datagroupName',
              placeholder: '请输入数据组名称',
              anchor: 24
            },
            {
              label: '是否启用',
              prop: 'isEnable',
              xType: 'switch',
              anchor: 24,
              'active-value': 1,
              'inactive-value': 0
            },
            {
              label: '描述',
              prop: 'datagroupNote',
              type: 'textarea',
              rows: 4,
              placeholder: '请输入数据组描述',
              anchor: 24
            }
          ],
          rules: {
            datagroupCode: [
              { required: true, message: '请输入数据组编码', trigger: 'blur' }
            ],
            datagroupName: [
              { required: true, message: '请输入数据组名称', trigger: 'blur' }
            ],
            isEnable: [
              { required: true, message: '请选择是否启用', trigger: 'blur' }
            ]
          },
          title: '新增数据组',
          type: 'ADD',
          ref: 'addForm',
          submitBtnList: [
            {
              label: '保存',
              methods: 'handleAddSubmit',
              icon: 'el-icon-circle-check-outline',
              type: 'primary',
              disabled: false
            },
            {
              label: '取消',
              methods: 'handleCancel',
              icon: 'el-icon-circle-close-outline',
              disabled: false
            }
          ]
        },
        edit: {
          model: {
            datagroupCode: '',
            datagroupName: '',
            datagroupNote: '',
            isEnable: 1,
            createdTime: '',
            creator: '',
            isDeleted: '',
            datagroupId: ''
          },
          fields: [
            {
              label: '数据组编码',
              prop: 'datagroupCode',
              placeholder: '请输入数据组编码',
              anchor: 24,
              ref: 'funId'
            },
            {
              label: '数据组名称',
              prop: 'datagroupName',
              placeholder: '请输入数据组名称',
              anchor: 24
            },
            {
              label: '是否启用',
              prop: 'isEnable',
              xType: 'switch',
              anchor: 24,
              'active-value': 1,
              'inactive-value': 0
            },
            {
              label: '描述',
              prop: 'datagroupNote',
              type: 'textarea',
              rows: 4,
              placeholder: '请输入数据组描述',
              anchor: 24
            }
          ],
          rules: {
            datagroupCode: [
              { required: true, message: '请输入数据组编码', trigger: 'blur' }
            ],
            datagroupName: [
              { required: true, message: '请输入数据组名称', trigger: 'blur' }
            ],
            isEnable: [
              { required: true, message: '请选择是否启用', trigger: 'blur' }
            ]
          },
          title: '编辑数据组',
          type: 'EDIT',
          ref: 'editForm',
          submitBtnList: [
            {
              label: '保存',
              methods: 'handleEditSubmit',
              icon: 'el-icon-circle-check-outline',
              type: 'primary',
              disabled: false
            },
            {
              label: '取消',
              methods: 'handleCancel',
              icon: 'el-icon-circle-close-outline',
              disabled: false
            }
          ]
        }
      }
    }
  },
  created() {
    // 对初始 this.formPanel.edit.model 进行深拷贝
    this.editModelInitialData = deepClone(this.formPanel.edit.model)
    // this.getAllCodeTypeListDataInfo()
    // this.getResultsymbolDataInfo()
    // this.getBusinessobject()
  },
  beforeCreate() {
    // 根据页面路由找出有权限访问的 url 数组
    const urlArr = ((this.$route.meta && this.$route.meta.children) || []).map(
      item => item.url
    )

    this.toolPanelBtns = [
      {
        label: '新增',
        methods: 'handleAdd',
        url: '/v1/yq/datagroup/add',
        icon: 'el-icon-circle-plus-outline',
        type: 'primary',
        disabled: false
      }
    ].filter(item => item.url && urlArr.includes(item.url))

    this.tableRowBtns = [
      {
        label: '编辑',
        methods: 'handleEdit',
        url: '/v1/yq/datagroup/update',
        icon: 'el-icon-edit-outline',
        type: 'primary',
        key: 'edit',
        align: 'top-start',
        disabled: false
      },
      {
        label: '条件配置',
        methods: 'handleConditionConfig',
        url: '/v1/yq/datagroup/update',
        svgIcon: 'tjconfig',
        type: '',
        key: '',
        align: 'top-start',
        disabled: false
      },
      {
        label: '增加表权限',
        methods: 'handleAddTableAuth',
        url: '/v1/yq/datagroup/update',
        icon: 'el-icon-circle-plus-outline',
        type: 'primary',
        key: 'edit',
        align: 'top-start',
        disabled: false
      },
      {
        label: '表及字段权限配置',
        methods: 'handleTableFieldAuth',
        url: '/v1/yq/datagroup/update',
        svgIcon: 'mdtjconfig',
        type: '',
        key: '',
        align: 'top-start',
        disabled: false
      },
      {
        label: '查看',
        methods: 'handleLook',
        url: '/v1/yq/datagroup/update',
        icon: 'el-icon-view',
        type: 'primary',
        key: 'edit',
        align: 'top-start',
        disabled: false
      },
      {
        label: '删除',
        methods: 'handleDelete',
        url: '/v1/yq/datagroup/delete',
        icon: 'el-icon-delete',
        type: 'danger',
        key: 'delete',
        align: 'top-start',
        disabled: false
      }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.addRightBtns = [
      {
        label: '全选并保存',
        methods: 'handleAddAllSave',
        url: '/v1/yq/datagroup/addTableConfig',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '保存',
        methods: 'handleAddRightSave',
        url: '/v1/yq/datagroup/addTableConfig',
        icon: 'el-icon-circle-check-outline',
        type: 'primary',
        disabled: false
      },
      {
        label: '取消',
        methods: 'handleCancel',
        url: '/v1/yq/datagroup/addTableConfig',
        icon: 'el-icon-circle-close-outline',
        type: 'primary',
        disabled: false
      }
    ].filter(item => item.url && urlArr.includes(item.url))
  },
  methods: {
    setClassName(id) {
      return `el-tooltip__popper is-dark username-popover username-${id}-popover`
    },
    showContent(id, userName) {
      this.$nextTick(() => {
        const popover = document.getElementsByClassName(
          `username-${id}-popover`
        )[0]
        popover.classList.remove('el-popover')
        popover.classList.remove('el-popper')
      })
    },
    // 条件配置
    handleConditionConfig(row) {
      this.datagroupName = row.datagroupName
      this.datagroupId = row.datagroupId
      this.dialogType = 'condition'
    },
    // 增加表权限
    handleAddTableAuth(row) {
      this.dialogType = 'AddRIGHT'
      this.datagroupId = row.datagroupId
      this.datagroupName = row.datagroupName
      this.addRightTitle = `数据组 ${row.datagroupName} 增加表权限`
    },
    // 表及字段权限配置
    handleTableFieldAuth(row) {
      this.datagroupId = row.datagroupId
      this.datagroupName = row.datagroupName
      this.dialogType = 'TableFieldAuth'
    },
    handleCurrentChange() {},
    handleLook(row) {
      this.$router.push({
        path: `/siteconfig/datagroup/src/datagroupLook/${row.datagroupId}`
      })
    },
    handleInputClick(ev, val) {
      const params = {}
      params.q_name = val
      this.store._searchParams = params
      this.$refs.table.load(1, this.store.limit)
    },
    handleCurrentChange() {},
    handleCancel() {
      this.$refs.addForm && this.$refs.addForm.clearValidate()
      this.$refs.editForm && this.$refs.editForm.clearValidate()
      this.dialogType = ''
    },
    handleAddAllSave() {
      const params = this.$refs.addtableright.getSearchModelData()
      if (!params.dbId) {
        this.$message({
          customClass: 'datagroup-message',
          type: 'info',
          message: '数据源必选！'
        })
        return
      }
      // 加载 loading
      const loading = this.$loading({
        fullscreen: true,
        text: '请求发送中，请稍候',
        customClass: 'addall-loading'
      })
      this.addTableConfig(params, this.addBatchTableConfigUrl)
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.dialogType = ''
          }
        })
        .catch(err => console.log('err', err))
        .then(() => {
          // 以服务的方式调用的 Loading 需要异步关闭
          this.$nextTick(() => {
            loading.close()
          })
        })
    },
    handleAddRightSave() {
      const selectedList = this.$refs.addtableright.selectedList
      if (selectedList.length === 0) {
        this.$message({
          type: 'error',
          message: '请配置数据'
        })
        return
      }
      const params = {}
      params.datagroupId = this.datagroupId
      params.tableConfigs = JSON.stringify(
        selectedList.map(item => {
          return {
            dsId: item.dbId,
            firstCatId: item.firstCatId,
            secondCatId: item.secondCatId,
            tableId: item.tableId,
            fields: item.fields
          }
        })
      )
      this.$refs.addRightBtns.handleChangeStatus('handleAddRightSave', {
        loading: true,
        icon: ''
      })
      this.addTableConfig(params)
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.dialogType = ''
            this.$refs.table.load(1, this.store.limit)
            this.$refs.addtableright.$refs.table.clearSelection()
          }
          this.$refs.addRightBtns.handleChangeStatus('handleAddRightSave', {
            loading: false,
            icon: 'el-icon-circle-check-outline'
          })
        })
        .catch(err => {
          console.log('err', err)
        })
    },
    handleAddRightCancel() {
      this.dialogType = ''
    },
    // eslint-disable-next-line
    renderCustom(h) {
      if (this.dialogType === 'condition') {
        return (
          <DialogForm
            closeOnClickModal={false}
            width='1180px'
            class='condition-dialog'
            modalAppendToBody={true}
            visible={this.dialogType === 'condition'}
            title={`${this.datagroupName}条件配置`}
            on-close={this.handleCancel}>
            <ConditionConfig
              datagroupId={this.datagroupId}
              datagroupName={this.datagroupName}
            />
            <c-form ref='form' slot='footer'>
              <c-form-item class='submit-btn'>
                <ButtonList operateBtnList={this.submitBtnList}></ButtonList>
              </c-form-item>
            </c-form>
          </DialogForm>
        )
      } else if (this.dialogType === 'TableFieldAuth') {
        return (
          <DialogForm
            closeOnClickModal={false}
            width='1180px'
            class='tableFieldAuth-dialog'
            modalAppendToBody={true}
            visible={this.dialogType === 'TableFieldAuth'}
            title={`数据组${this.datagroupName}增加表权限`}
            on-close={this.handleCancel}>
            <TableFieldAuth
              datagroupId={this.datagroupId}
              datagroupName={this.datagroupName}
            />
          </DialogForm>
        )
      } else if (this.dialogType === 'AddRIGHT') {
        return (
          <DialogForm
            width='1180px'
            modalAppendToBody={true}
            closeOnClickModal={false}
            visible={this.dialogType === 'AddRIGHT'}
            title={this.addRightTitle}
            class='table-right-dialog'
            on-close={() => {
              this.dialogType = ''
            }}>
            <addtableright
              ref='addtableright'
              datagroupId={this.datagroupId}
              datagroupName={this.datagroupName}
            />
            <c-form ref='form' slot='footer'>
              <c-form-item class='submit-btn'>
                <ButtonList
                  ref='addRightBtns'
                  operateBtnList={this.addRightBtns}></ButtonList>
              </c-form-item>
            </c-form>
          </DialogForm>
        )
      }
    }
  }
}
</script>

<style lang="scss">
.datagroup {
  .searchPanel {
    padding-bottom: 0;
    .search-btn-box {
      bottom: 0;
    }
  }
  .table-name {
    color: #333;
    // line-height:0.8rem;
    word-break: break-all;
    text-overflow: ellipsis; //显示为省略号
    display: -webkit-box; //对象作为伸缩盒子模型显示
    -webkit-box-orient: vertical; //设置或检索伸缩盒对象的子元素的排列方式
    -webkit-line-clamp: 2; //显示行数## 标题文字 ##
    overflow: hidden;
  }
}
.condition-dialog {
  .el-dialog__footer {
    display: none;
  }
}
.tableFieldAuth-dialog {
  .el-dialog__body {
    padding: 20px 0;
    .searchPanel {
      padding-bottom: 0;
      .search-btn-box {
        bottom: 0;
      }
    }
    .el-form {
      width: auto;
    }
    .el-pagination__sizes {
      .el-select {
        width: 80px;
      }
    }
  }
  .el-dialog__footer {
    display: none;
  }
}
.table-right-dialog {
  .el-dialog__body {
    .el-form {
      width: auto;
    }
  }
}
.addall-loading {
  background: #000;
  opacity: 0.5;
}
</style>
